﻿namespace Triad.Web.UI
{
    using System;
    using System.Collections;
    using System.Configuration;
    using System.Web.UI;
    using Triad.Common;
    using System.Web.UI.WebControls;
    using System.Web.UI.HtmlControls;

    /// <summary>
    /// Global Page Settings
    /// </summary>
    /// public class BasePage : System.Web.UI.Page
    public class Page : System.Web.UI.Page
    {
        protected store.User userObj;
        protected ArrayList userPerms;
        protected bool IncludeJQuery = false;

        public void AddCSS(string name, string p)
        {
            var cssLink = new HtmlLink { Href = ResolveClientUrl(p), ID = name };
            cssLink.Attributes.Add("rel", "stylesheet");
            cssLink.Attributes.Add("type", "text/css");
            Page.Header.Controls.Add(cssLink);
        } //Page_Load
        
        public void AddJS(string name, string jsFile, ClientScriptManager cm)
        {
            cm.RegisterClientScriptInclude(GetType(), name, ResolveClientUrl(jsFile));
        }

        protected override void OnInit(EventArgs e)
        {
            bool isLogon = Request.RawUrl.StartsWith("/mainmenu.aspx?t=logon", StringComparison.CurrentCultureIgnoreCase);
            if (!isLogon && !User.Identity.IsAuthenticated)
            {
                Response.Redirect("/MainMenu.aspx?T=Logon");
            }


            if (!isLogon)
            {
                if (Session["UserObj"] == null)
                {
                    var noUser = new Exception("In Page.CS, Session[UserObj] was null");
                    Utility.WriteLog(noUser);
                    Response.Redirect("~/MainMenu.aspx?T=Logon");
                }
                
                if(userObj==null) userObj = new store.User();

                string cssTheme="/_fw/theme/red";
                string sTmp = "/_fw/controls/";
                if (!String.IsNullOrEmpty(ConfigurationManager.AppSettings["Triad.Controls"]))
                {
                    sTmp = ConfigurationManager.AppSettings["Triad.Controls"];
                }
                if(!String.IsNullOrEmpty(userObj.Theme))
                {
                    cssTheme = userObj.Theme;
                }
                else if (!String.IsNullOrEmpty(ConfigurationManager.AppSettings["Theme"]))
                {
                    cssTheme = ConfigurationManager.AppSettings["Theme"];
                }

                ClientScriptManager cm = Page.ClientScript;

                if (!Page.Request.Url.ToString().Contains("MainMenu.aspx"))
                {
                    if (!cm.IsClientScriptIncludeRegistered("tfCore"))
                    {
                        AddJS("tfcore", sTmp + "js/jquery.js", cm);
                        AddJS("tfcore2", sTmp + "js/jquery-ui.js", cm);
                        AddJS("tfcore3", sTmp + "js/tfcore.js", cm);
                        AddJS("tfcore4", sTmp + "js/appcommon.js", cm);
                    }
                    AddCSS("cssCommon", cssTheme + "/appcommon.css" );
                    AddCSS("cssClueTip",cssTheme + "/jquery.cluetip.css");
                }
                
                    try
                    {
                        userPerms = (ArrayList) Session["userPerms"];

                    }
                    catch (Exception ex)
                    {
                        Utility.WriteLog(ex);
                        Response.Redirect("/MainMenu.aspx?T=Logon");
                    }
            }

        base.OnInit(e);
        }


        protected override void OnUnload(EventArgs e)
        {
            userObj = null;
            base.OnUnload(e);
        }

        /// <summary>
        /// Checks whether or not a logged in user has access to an item/element. (Based on string representation of the item)
        /// </summary>
        /// <param name="SecuredItem">The P_STR secured item.</param>
        /// <returns></returns>
        public bool CheckAccess(string SecuredItem)
        {
            // presume they can use the item
            var rtn = true; 

            // if they are on the deny list, change the return value
            //if (userPerms.Contains(SecuredItem)) rtn = false;

            return rtn;
        }


        /// <summary>
        /// Returns the JSPanel (used in injecting javascript onto a page).  If one doesn't exist, will create it.
        /// </summary>
        /// <value>The JS panel.</value>
        public Panel JSPanel
        {
            get
            {
                Panel tempPanel = (Panel)Page.FindControl("JSPanel");
                if (tempPanel == null)
                {
                    tempPanel = new Panel() { ID = "JSPanel" };
                    Page.Form.Controls.Add(tempPanel);
                }
                return tempPanel;
            }
        }

        
        // *** Possible to enable the below two functions to speed up 
        // *** transfers by placing the ViewState in a Session Variable.

        ///// <summary>
        ///// Loads any saved view-state information into the Page object
        ///// </summary>
        ///// <returns></returns>
        //protected override object LoadPageStateFromPersistenceMedium()
        //{
        //    object viewState;

        //    try
        //    {
        //        LosFormatter lf = new LosFormatter();
        //        viewState = lf.Deserialize((string)Session["ViewState"]);
        //    }

        //    catch
        //    {
        //        throw new HttpException("The View State is invalid or corrupted");
        //    }

        //    return viewState;
        //}



        ///// <summary>
        ///// Caches ViewState information in session rather than in default hidden field.
        ///// </summary>
        ///// <param name="viewState"></param>

        //protected override void SavePageStateToPersistenceMedium(object viewState)
        //{
        //    LosFormatter lf = new LosFormatter();
        //    System.IO.StringWriter sw = new System.IO.StringWriter();
        //    lf.Serialize(sw, viewState);
        //    Session["ViewState"] = sw.ToString();

        //}
    
    }
}
